<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="100px">
      <el-form-item label="图片" prop="filePath">
        <el-upload
          class="avatar-uploader"
          :action="sysConstant.FILE_UPLOAD_PATH"
          :show-file-list="false"
          :headers="{'token':token}"
          :on-success="handleAvatarSuccess">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="标题/描述" prop="title">
        <el-input v-model="dataForm.title" placeholder="请输入标题/描述"></el-input>
      </el-form-item>
      <el-form-item label="所属模块" prop="moduleId">
        <el-select v-model="dataForm.moduleId" placeholder="请选择图片类型">
          <el-option v-for="(item,index) in moduleList" :key="index" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-divider>以下轮播图生效</el-divider>
      <el-form-item label="关联文章" prop="contentId">
        <el-select filterable
                   remote  :remote-method="remoteMethod"
                   :loading="loading" v-model="dataForm.contentId" placeholder="请选择文章">
          <el-option v-for="(item,index) in contentList" :key="index" :label="item.title" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="外部链接" prop="url">
        <el-input v-model="dataForm.url" placeholder="请输入外部链接"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="orderNum">
        <el-input v-model="dataForm.orderNum" placeholder="请输入排序"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        filePath: '',
        moduleId: '',
        title: '',
        orderNum:0,
        contentId:'',
        url:''
      },
      dataRule: {
        filePath: [
          {required: true, message: '图片不能为空', trigger: 'blur'}
        ],
        moduleId: [
          {required: true, message: '所属模块不能为空', trigger: 'blur'}
        ],
        // title: [
        //   {required: true, message: '标题/描述不能为空', trigger: 'blur'}
        // ],
        orderNum: [
          {required: true, message: '排序不能为空', trigger: 'blur'}
        ],
      },
      imageUrl: '',
      sysConstant: this.sysConstant,
      token:this.$cookie.get('token'),
      moduleList:[],
      contentList:[],
      loading: false,
    }
  },
  methods: {
    init(id) {
      this.getModuleList()
      this.dataForm.id = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/mh/banner/info/${this.dataForm.id}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.filePath = data.data.filePath
              this.dataForm.moduleId = data.data.moduleId
              this.dataForm.title = data.data.title
              this.dataForm.orderNum = data.data.orderNum
              this.dataForm.contentId = data.data.contentId
              this.dataForm.url = data.data.url
              this.imageUrl = this.sysConstant.FILE_SRC_PATH+data.data.filePath
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/mh/banner/${!this.dataForm.id ? 'save' : 'update'}`),
            method: !this.dataForm.id ? 'post' : 'put',
            data: this.$http.adornData({
              'id': this.dataForm.id || undefined,
              'filePath': this.dataForm.filePath,
              'moduleId': this.dataForm.moduleId,
              'title': this.dataForm.title,
              'contentId': this.dataForm.contentId,
              'url': this.dataForm.url,
              'orderNum':this.dataForm.orderNum
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },

    handleAvatarSuccess(res, file) {
      console.log(res)
      console.log(file)
      if (res.success) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.dataForm.filePath = res.data[0].path
      } else {
        this.$message({
          message: res.msg,
          type: 'success',
          duration: 1500,
        })
      }

    },

    getModuleList(){
      this.$http({
        url: this.$http.adornUrl(`/mh/module/list`),
        method: 'get',
        params: this.$http.adornParams({typeListStr:[0,1].join()})
      }).then(({data}) => {
        if (data.success) {
          this.moduleList = data.data
        }
      })
    },

    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        this.getContentList(query)
      } else {
        this.contentList = [];
      }
    },

    getContentList(query){
      this.$http({
        url: this.$http.adornUrl(`/mh/content/list`),
        method: 'get',
        params: this.$http.adornParams({'title':query})
      }).then(({data}) => {
        this.loading = false
        if (data.success) {
          this.contentList = data.data
        }
      })
    }


  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

